package com.chucang.shucang.ttp.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.chucang.shucang.common.mq.to.ClosePayInfoTO;
import com.chucang.shucang.ttp.vo.PayInfoVO;
import com.chucang.shucang.common.mq.to.TransferTO;
import com.chucang.shucang.ttp.paycenter.bo.AliPayBizBO;
import com.chucang.shucang.ttp.paycenter.bo.GoodsDetail;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/22 18:24
 * @description 支付宝支付
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AliPayService {
    private final DefaultAlipayClient alipayClient;

    @Value("${pay.alipay.notifyUrl}")
    private String notifyUrl;

    /**
     * 支付宝支付接口 订单和账单业务
     *
     * @param payInfoVO 订单to
     * @throws AlipayApiException e
     */
    public AlipayTradeAppPayResponse payForOrder(PayInfoVO payInfoVO) throws AlipayApiException {
        //获取订单信息
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //异步通知
        request.setNotifyUrl(notifyUrl);
        AliPayBizBO aliPayBizBO = new AliPayBizBO();
        Date date = new Date();
        DateTime dateTime = DateUtil.offsetMinute(date, 6);
        String timeOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dateTime);
        List<GoodsDetail> goodsDetailList = new ArrayList<>(1);
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoods_name(payInfoVO.getProductName());
        goodsDetail.setGoods_id(payInfoVO.getProductId());
        goodsDetail.setQuantity(payInfoVO.getQuantity());
        goodsDetail.setPrice(payInfoVO.getPrice());
        goodsDetailList.add(goodsDetail);
        aliPayBizBO
                .setSubject(payInfoVO.getSubject())
                .setProduct_code("QUICK_MSECURITY_PAY")
                .setTime_expire(timeOut)
                .setTotal_amount(payInfoVO.getOrderAmount())
                .setPassback_params(payInfoVO.getType().toString())
                .setGoods_detail(goodsDetailList);
        if (payInfoVO.getType() == 2) {
            aliPayBizBO.setOut_trade_no(payInfoVO.getBillSn());
        } else {
            aliPayBizBO.setOut_trade_no(payInfoVO.getOrderSn());
        }
        request.setBizContent(JSONUtil.toJsonStr(aliPayBizBO));
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        if (response.isSuccess()) {
            log.info("订单或账单号===》{}支付请求发送成功！", payInfoVO.getOrderSn() == null ? payInfoVO.getBillSn() : payInfoVO.getOrderSn());
            //返回订单信息
            return response;
        } else {
            log.error("订单或账单号===》{}支付请求处理失败，异常信息为:{}", payInfoVO.getOrderSn() == null ? payInfoVO.getBillSn() : payInfoVO.getOrderSn(), response.getSubMsg());
            return null;
        }
    }

    /**
     * 支付宝关单接口 订单业务
     *
     * @param closePayInfoTO 关单to
     * @throws AlipayApiException e
     */
    public void closeOrder(ClosePayInfoTO closePayInfoTO) throws AlipayApiException {
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", closePayInfoTO.getOrderSn());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            log.info("订单号===》{}关单请求发送成功！", closePayInfoTO.getOrderSn());
        } else {
            log.error("订单号===》{}关单请求处理失败，异常信息为:{}", closePayInfoTO.getOrderSn(), response.getSubMsg());
        }
    }

    /**
     * 转账 提现 账单业务
     *
     * @param transferTO 转账to
     * @throws AlipayApiException e
     */
    public boolean transferBill(TransferTO transferTO) throws AlipayApiException {
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
        model.setOutBizNo(transferTO.getBillSn());
        model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
        model.setBizScene("DIRECT_TRANSFER");
        Participant payeeInfo = new Participant();
        payeeInfo.setIdentity(transferTO.getPayeeAccount());
        payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
        payeeInfo.setName(transferTO.getUsername());
        model.setPayeeInfo(payeeInfo);
        model.setTransAmount(transferTO.getTransAmount());
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");
        model.setOrderTitle(transferTO.getBillTitle());
        request.setBizModel(model);
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            log.info("账单号===》{}转账请求处理成功！", transferTO.getBillSn());
            return true;
        } else {
            log.error("账单号===》{}转账请求失败，失败信息为：{}", transferTO.getBillSn(), response.getSubMsg());
            return false;
        }
    }
}
